package site.anxuan.seckill.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import site.anxuan.seckill.common.BusinessException;
import site.anxuan.seckill.common.ErrorCode;
import site.anxuan.seckill.common.Tools;
import site.anxuan.seckill.dao.UserDao;
import site.anxuan.seckill.entity.User;
import site.anxuan.seckill.service.UserService;
import site.anxuan.seckill.validator.ObjectValidator;

import java.util.Map;

@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    private final RedisTemplate<String, Object> redisTemplate;

    private final ObjectValidator validator;

    private final UserDao userDao;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User login(String phone, String password) {
        if (!StringUtils.hasText(phone) || !StringUtils.hasText(password)) {
            throw new BusinessException(ErrorCode.USER_LOGIN_FAILED, "参数不合法");
        }
        User user = userDao.selectByPhone(phone);
        if (!user.getPassword().equals(password)) {
            throw new BusinessException(ErrorCode.USER_LOGIN_FAILED, "账号或密码错误!");
        }
        return user;
    }

    @Override
    @Transactional
    public void register(User user) {
        Map<String, String> validate = validator.validate(user);
        if (validate != null) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR,
                    String.join(",", validate.values()) + "！");
        }
        user.setPassword(Tools.md5(user.getPassword()));
        userDao.insert(user);
    }

}
